package com.yonyou.cyxdms.sysAuth.service.service.broker;


import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;

import javax.imageio.ImageIO;

import com.yonyou.cyxdms.sysAuth.service.config.SimsunFont;
import com.yonyou.cyxdms.sysAuth.service.vo.user.Poster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.font.FontDesignMetrics;

public class PosterUtil {
    private static final Logger logger = LoggerFactory.getLogger(PosterUtil.class);

    static Poster initPoster(Poster poster1) {
        Poster poster = new Poster();
        //画布
        poster.setWidth(poster1.getWidth());
        poster.setHeight(poster1.getHeight());
        //头像
      /* poster.setAvatarUrl(avatarUrl);
       poster.setCircle(true);
       poster.setAvatarX((int)(width/11.5));
       poster.setAvatarY(height/28);
       poster.setAvatarWidth(width/6);
       poster.setAvatarHeight(width/6);
       //名字
       poster.setName(name);
       poster.setNameFont(new Font("宋体",Font.PLAIN,width/24));
       poster.setNameColor(new Color(33,33,33));
       poster.setNameX(poster.getAvatarX()+poster.getAvatarWidth()+20);
       poster.setNameY(poster.getAvatarY()+poster.getAvatarHeight()/2+15);*/
        //商品
        poster.setGoodsUrl(poster1.getGoodsUrl());
        poster.setGoodsWidth(295); //banner图宽度填充满
        poster.setGoodsHeight(392);
        //poster.setGoodsX((poster_.getWidth()-poster.getGoodsWidth())/2);
        //poster.setGoodsY(poster.getAvatarY()+poster.getAvatarHeight()); //+100是往下移动

        poster.setGoodsX(20);
        poster.setGoodsY(0); //+100是往下移动

        //测评结果
        poster.setDesc(poster1.getName());
        poster.setDescColor(Color.BLACK);
        int size = poster1.getWidth() / 17;
        System.out.println("size:" + size);
        //poster.setDescFont(new Font("宋体",Font.PLAIN,18));
        //poster.setDescX((poster_.getWidth()-"测评结果".length()*size)/6-15);
        //poster.setDescY(poster.getGoodsY()+poster.getGoodsHeight()+(int)(poster_.getHeight()/21.3)+15);

        poster.setDescFont(getSimsun(Font.PLAIN, 32));
        poster.setDescColor(new Color(58, 58, 58));
        poster.setDescX(360);
        poster.setDescY(140);

        //测评结果标题
        poster.setPrice(poster1.getDealerName());
        poster.setPriceColor(new Color(58, 58, 58));
        poster.setPriceFont(getSimsun(Font.PLAIN, 16));
        //poster.setPriceX((poster_.getWidth()-poster_.getPrice().length()*size)/5);
        //poster.setPriceY(poster.getGoodsY()+poster.getGoodsHeight()+(int)(poster_.getHeight()/10.6)+18);

        poster.setPriceX(340);
        poster.setPriceY(170);

        //测评说明
        poster.setResult(poster1.getDealerName());
        poster.setResultColor(new Color(58, 58, 58));
        poster.setResultFont(getSimsun(Font.PLAIN, 0));
        //poster.setResultX((poster_.getWidth()-"测评说明".length()*size)/6-15);
        //poster.setResultY(poster.getGoodsY()+poster.getGoodsHeight()+(int)(poster_.getHeight()/21.3)+90);
        //poster.setResultX(370);
        //poster.setResultY(150);

        //测评说明描述
        poster.setResult_content(poster1.getDesc());
        poster.setResult_contentColor(new Color(58, 58, 58));
        poster.setResult_contentFont(getSimsun(Font.PLAIN, 20));
        poster.setResult_contentX(290);
        poster.setResult_contentY(340);

        System.out.println(poster.getResult_contentX() + "-" + poster.getResult_contentY());


        //小程序码
        poster.setQrCodeUrl(poster1.getQrCodeUrl());
        poster.setQrCodeWidth(612);
        //poster.setQrCodeWidth((int)(poster_.getWidth()/2.85));
        //poster.setQrCodeHeight((int)(poster_.getWidth()/2.85));
        poster.setQrCodeHeight(490);
        //poster.setQrCodeX((int)(poster_.getWidth()/16.5));
        //poster.setQrCodeY(poster_.getHeight()-poster.getQrCodeHeight()-(int)(poster_.getHeight()/7.68));

        poster.setQrCodeX(0);
        poster.setQrCodeY(0);

        //tips1
        poster.setTip1(poster1.getPhone());
        poster.setTip1Color(new Color(58, 58, 58));
        //poster.setTip1Font(new Font("宋体",Font.PLAIN,poster_.getWidth()/21));
        poster.setTip1Font(getSimsun(Font.PLAIN, 20));
        poster.setTip1X(poster.getQrCodeX() + poster.getQrCodeWidth() + 20);
        //poster.setTip1Y(poster.getQrCodeY()+poster.getQrCodeHeight()/2+10);
        poster.setTip1Y(100);
        //tips2
        poster.setTip2(poster1.getBrokerRule());//好物与好友一起分享
        poster.setTip2Color(new Color(58, 58, 58));
        poster.setTip2Font(getSimsun(Font.PLAIN, 20));
        poster.setTip2X(poster.getQrCodeX() + poster.getQrCodeWidth() - 30);
        poster.setTip2Y(poster.getQrCodeY() + poster.getQrCodeHeight() / 2 + 32 + 15);//90是这句问题与上面的间距
        //footer
        //poster.setFooterColor(new Color(34,173,32));
        //poster.setFooterWidth(145);
        //poster.setFooterHeight(50);
        //poster.setFooterX(240);
        //poster.setFooterY(430);
        //footer tips

        //TODO 注释底部文字
        //poster.setFooterTip("查看名片");
        //poster.setFooterTipColor(Color.white);
        //System.out.println(poster_.getWidth()/21);
        //poster.setFooterTipFont(new Font("宋体",Font.PLAIN,28));
        //poster.setFooterTipX(255);
        //poster.setFooterTipY(465);
        return poster;
    }

    static BufferedImage drawPoster(Poster poster) throws Exception {
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(poster.getResult_contentFont());


        long startTime = System.currentTimeMillis();
        String qrCodeUrl = poster.getQrCodeUrl();
        String goodsUrl = poster.getGoodsUrl();
        String avatarUrl = poster.getAvatarUrl();
        BufferedImage qrCodeImage = ImageIO.read(new URL(qrCodeUrl));
        BufferedImage goodsImage = ImageIO.read(new URL(goodsUrl));
        int width = poster.getWidth();
        int height = poster.getHeight();
        //画布
        BufferedImage canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        g.setBackground(new Color(230, 230, 230));//设置背景色
        g.clearRect(0, 0, width, height);

        // 设置文字抗锯齿
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
       /*//圆形头像
       BufferedImage newAvatar = circle(avatarUrl,poster.getAvatarWidth());
       //画头像
       g.drawImage(newAvatar.getScaledInstance(newAvatar.getWidth(), newAvatar.getHeight(), Image.SCALE_SMOOTH), poster.getAvatarX(), poster.getAvatarY(), null);
       // 4. 写字（昵称）
       g.setColor(poster.getNameColor());
       g.setFont(poster.getNameFont());
       g.drawString(poster.getName(), poster.getNameX(), poster.getNameY());*/
        //画商品
//       g.drawImage(Thumbnails.of(goodsImage).size(poster.getGoodsWidth(), poster.getGoodsHeight()).asBufferedImage(), poster.getGoodsX(), poster.getGoodsY(), null);
        g.drawImage(goodsImage.getScaledInstance(poster.getGoodsWidth(), poster.getGoodsHeight(), Image.SCALE_SMOOTH), poster.getGoodsX(), poster.getGoodsY(), null);
        //画小程序码
        g.drawImage(qrCodeImage.getScaledInstance(poster.getQrCodeWidth(), poster.getQrCodeHeight(), Image.SCALE_SMOOTH),
                poster.getQrCodeX(), poster.getQrCodeY(), null);

        //测评结果
        g.setColor(poster.getDescColor());
        g.setFont(poster.getDescFont());
        g.drawString(poster.getDesc(), poster.getDescX(), poster.getDescY());
        //测评结果标题
        //g.setColor(poster.getPriceColor());
        //g.setFont(poster.getPriceFont());
        //g.drawString(poster.getPrice(), poster.getPriceX(), poster.getPriceY());

        //画测评说明
        g.setColor(poster.getResultColor());
        g.setFont(poster.getResultFont());
        g.drawString(poster.getResult(), poster.getResultX(), poster.getResultY());


        //画测评说明描述
     /*  g.setColor(poster.getResult_contentColor());
       g.setFont(poster.getResult_contentFont());
       g.drawString("结婚苏丹发挥撒旦反对萨苏打法苏丹法苏丹法", poster.getResult_contentX()+25, poster.getResult_contentY());*/


        String zh = poster.getResult_content();
        int y = poster.getResult_contentY();
        //int length=zh.length();
        //if (length>0 && length<=10){
        //    g.setColor(poster.getResult_contentColor());
        //    g.setFont(poster.getResult_contentFont());
        //    String str="";
        //    for (int i = 0; i < 10-length; i++) {
        //        str+=" ";
        //    }
        //    g.drawString(str+zh, poster.getResult_contentX()+25, y);
        //} else if (length>10 && length <=18){
        //    g.setColor(poster.getResult_contentColor());
        //    g.setFont(poster.getResult_contentFont());
        //    g.drawString(zh.substring(0,10), poster.getResult_contentX()+25, y);
        //
        //    String str="";
        //    for (int i = 0; i < 20-length; i++) {
        //        str+=" ";
        //    }
        //    g.drawString(str+zh.substring(10,length), poster.getResult_contentX()+25, y+20);
        //} else {
        //    g.setColor(poster.getResult_contentColor());
        //    g.setFont(poster.getResult_contentFont());
        //    g.drawString(zh.substring(0,10), poster.getResult_contentX()+25, y);
        //
        //    g.drawString(zh.substring(10,18)+"...", poster.getResult_contentX()+25, y+20);
        //}


        String[] rows = makeLineFeed(zh, metrics, 210).split("\n");
        for (int i = 0; i < rows.length; i++) {
            g.setColor(poster.getResult_contentColor());
            g.setFont(poster.getResult_contentFont());
            if (i > 0) {
                y += 20;
            }
            if (i > 1) {
                break;
            } else if (i == 1) {
                if (rows.length > 2) {
                    String str = rows[i];
                    int cWidth = 0;
                    boolean flag = true;
                    while (flag) {
                        str = str.substring(0, str.length() - 1);
                        cWidth = getCharWidth(str + "...", metrics);
                        if (cWidth < 210) {
                            flag = false;
                        }
                    }
                    g.drawString(str + "...", poster.getResult_contentX() + 20 + 210 - cWidth, y);
                } else {
                    int cWidth = getCharWidth(rows[i], metrics);
                    g.drawString(rows[i], poster.getResult_contentX() + 20 + 210 - cWidth, y);
                }
                break;
            }
            int charWidth = getCharWidth(rows[i], metrics);
            g.drawString(rows[i], poster.getResult_contentX() + 20 + 210 - charWidth, y);

        }


        String[] resultRows = makeLineFeed(poster.getPrice(), metrics, 170).split("\n");
        System.out.println(resultRows.length);
        int priceY = poster.getPriceY();

        for (int i = 0; i < resultRows.length; i++) {
            g.setColor(poster.getPriceColor());
            g.setFont(poster.getPriceFont());
            if (i == 0) {
                g.drawString(resultRows[i] + "...", poster.getPriceX() + 25, priceY);
                break;
            }
        }


        //画tips1
        g.setColor(poster.getTip1Color());
        g.setFont(poster.getTip1Font());
        g.drawString(poster.getTip1(), poster.getResult_contentX() + 20 + 210 - getCharWidth(poster.getTip1(), metrics), metrics.getAscent() + 273);
        //画tips2
        g.setColor(poster.getTip2Color());
        g.setFont(poster.getTip2Font());
        g.drawString(poster.getTip2(), poster.getResult_contentX() + 20 + 210 - getCharWidth(poster.getTip2(), metrics), metrics.getAscent() + 224);
        //画底部栏
        //g.setColor(poster.getFooterColor());
        //g.fillRect(poster.getFooterX(),poster.getFooterY(),poster.getFooterWidth(),poster.getFooterHeight());
        //画底部栏提示
        //g.setColor(poster.getFooterTipColor());
        //g.setFont(poster.getFooterTipFont());
        //g.drawString(poster.getFooterTip(), poster.getFooterTipX(), poster.getFooterTipY());
        g.dispose();

        return canvas;
    }


    private static BufferedImage circle(String avatarImg, int width) throws Exception {
        BufferedImage avatar = ImageIO.read(new URL(avatarImg));
        BufferedImage newAvatar = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, width, width);
        Graphics2D g2 = newAvatar.createGraphics();
        newAvatar = g2.getDeviceConfiguration().createCompatibleImage(width, width, Transparency.TRANSLUCENT);
        g2 = newAvatar.createGraphics();
        g2.setComposite(AlphaComposite.Clear);
        g2.fill(new Rectangle(newAvatar.getWidth(), newAvatar.getHeight()));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2 = newAvatar.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.fillRoundRect(0, 0, width, width, width, width);
        g2.setComposite(AlphaComposite.SrcIn);
        g2.drawImage(avatar, 0, 0, width, width, null);
        g2.dispose();
        return newAvatar;
    }

    //文本换行处理
    public static String makeLineFeed(String zh, FontDesignMetrics metrics, int maxWidth) {
        StringBuilder sb = new StringBuilder();
        int lineWidth = 0;
        for (int i = 0; i < zh.length(); i++) {
            char c = zh.charAt(i);
            sb.append(c);
            // 如果主动换行则跳过
            if (sb.toString().endsWith("\n")) {
                lineWidth = 0;
                continue;
            }
            // FontDesignMetrics 的 charWidth() 方法可以计算字符的宽度
            int charWidth = metrics.charWidth(c);
            lineWidth += charWidth;
            // 如果当前字符的宽度加上之前字符串的已有宽度超出了海报的最大宽度，则换行
            if (lineWidth >= maxWidth - charWidth) {
                lineWidth = 0;
                sb.append("\n");
            }
        }
        return sb.toString();
    }


    //获取字符串像素
    public static int getCharWidth(String str, FontDesignMetrics metrics) {
        int lineWith = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int charWidth = metrics.charWidth(c);
            lineWith += charWidth;
        }
        return lineWith;
    }

    public static Font getSimsun(int style, int size) {
        return SimsunFont.createFont(style, size);
    }

}
